<?php
class SystemModel extends BpfModel
{
  public function rebuildPermissions()
  {
    $dir = SYSPATH . '/controllers';
    $list = $this->_getPermissionsDir($dir);
    $mysqlModel = $this->getModel('mysql');
    $mysqlModel->query('TRUNCATE `permissions`');
    $result = $mysqlModel->getSqlBuilder()
        ->insert('permissions', $list)
        ->query();
    return $result->affectedRows();
  }

  private function _getPermissionsDir($dir, $folder = null)
  {
    static $list = [];
    if ($dh = opendir($dir)) {
      while(false !== ($file = readdir($dh))) {
        if ($file[0] == '.' || strstr($dir, '/mobile')) {
          continue;
        }
        if (is_dir($dir . '/' . $file)) {
          $this->_getPermissionsDir($dir . '/' . $file, $file);
        } else {
          include_once $dir . '/' . $file;
          $cname = strtolower(basename($file, '.php'));
          $controllerClass = (isset($folder) ? ucfirst($folder) : '') .  ucfirst($cname) . 'Controller';
          if (class_exists($controllerClass, false) && method_exists($controllerClass, '__permissions')) {
            $permissions = call_user_func(array($controllerClass, '__permissions'));
            if (is_array($permissions) && isset($permissions['name']) && isset($permissions['permissions']) && is_array($permissions['permissions'])) {
              foreach ($permissions['permissions'] as $key => $desc) {
                $list[] = [
                  'permission' => $key,
                  'name' => isset($desc['name']) ? $desc['name']: ($permissions['name'] ?? ''),
                  'description' => $desc['desc'] ?? $desc,
                  'created' => Azalea\TIME,
                ];
              }
            }
          }
        }
      }
      closedir($dh);
    }
    return $list;
  }

}




